<template>
  <div class="h-full overflow-auto">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" @click="handleUpdateOrders"> 保存排序 </a-button>
      </template>

      <template #move>
        <!-- &#10019 -->
        &#9769
        <!-- <drag-outlined class="cursor-move" /> -->
      </template>
      <template #fieldWrite="{ text, record, index }">
        <div class="mt-2">
          <a-button
            class="ml-2"
            
            :type="text ? 'primary' : 'default'"
            @click="handleSelectFieldWriteText(record, index, 'fieldWrite')"
          >
            选择
          </a-button>
        </div>
      </template>
      <template #fieldHide="{ text, record, index }">
        <div class="mt-2">
          <a-button
            class="ml-2"
            
            :type="text ? 'primary' : 'default'"
            @click="handleSelectFieldWriteText(record, index, 'fieldHide')"
          >
            选择
          </a-button>
        </div>
      </template>
      <template #fieldExport="{ text, record, index }">
        <div class="mt-2">
          <a-button
            class="ml-2"
            
            :type="text ? 'primary' : 'default'"
            @click="handleSelectFieldWriteText(record, index, 'fieldExport')"
          >
            选择
          </a-button>
        </div>
      </template>

      <template #authority="{ record }">
        <div class="text-left">
          <div>
            <Checkbox
              v-for="(item, ind) in authList.filter((_, index) => index < 9)"
              :key="ind"
              :title="item.message ? item.message : ''"
              :checked="record[item.value] == 1 ? true : false"
              @change="handleAuthorityChange($event, record, item.value)"
              >{{ item.label }}</Checkbox
            >
          </div>
          <div>
            <Checkbox
              v-for="(item, ind) in authList.filter((_, index) => index >= 9)"
              :key="ind"
              :title="item.message ? item.message : ''"
              :checked="record[item.value] == 1 ? true : false"
              @change="handleAuthorityChange($event, record, item.value)"
              >{{ item.label }}</Checkbox
            >
          </div>
        </div>
      </template>
      <template #filterCond="{ text, record }">
        <div>
          <a-button
            
            :type="text ? 'primary' : 'default'"
            @click="handleFilterModal(text, record.id, record.filterUnitCode)"
          >
            配置
          </a-button>
        </div>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'leftBottom',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <SelectAll @register="registerSelectAllModal" @success="handleSuccess" />
    <SelectFieldWriteTextModal
      @register="registerModalSelectFieldWriteText"
      @success="handleSuccessSelectFieldWriteText"
    />
    <FilterModal @register="registerModalFilterModal" @success="handleSuccessFilterModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, watch, nextTick, onMounted } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getAdminFlowListPriv,
    getAdminFlowCreatePriv,
    getAdminFlowUpdatePriv,
    getAdminFlowDelPriv,
  } from '/@/api/flowManage/flowManage';
  import {
    getVisualListPriv,
    getVisualUpdatePriv,
    getVisualSetFieldWrite,
    getVisualSetFieldHide,
    getVisualSetFieldExport,
    getVisualCreatePriv,
    getVisualDelPriv,
    getVisualUpdateOrders,
  } from '/@/api/module/module';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { SelectAll } from '/@/components/CustomComp';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { columns, authorityList } from './authorityComponent.data';
  import SelectFieldWriteTextModal from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/nodeEdit/modules/SelectFieldWriteTextModal.vue';
  import FilterModal from './FilterModal.vue';
  import { Checkbox } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      SelectAll,
      SelectFieldWriteTextModal,
      FilterModal,
      Checkbox,
    },
    props: {
      moduleCode: {
        type: String,
        default: '',
      },
      formCode: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const [registerSelectAllModal, { openModal }] = useModal();
      const { createMessage } = useMessage();
      const { t } = useI18n();
      const currentRecord = ref<Recordable>({});
      const dataSource = ref([]);
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const authList = ref<Recordable>([]);

      const [registerTable, { reload, setProps, setTableData, getDataSource }] = useTable({
        title: '权限',
        api: getVisualListPriv,
        columns,
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        beforeFetch: (info) => {
          return {
            ...info,
            moduleCode: props.moduleCode,
          };
        },
        afterFetch: (data) => {
          data.forEach((item) => {
            item.import = item.importXls;
            item.export = item.exportXls;
            item.isFilter = item.filter ? 1 : 0;
          });
          return data;
        },
        // immediate: false,
        pagination: false, //无分页
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
        customRow: customRow,
      });

      onMounted(() => {
          if (!serverInfo.isFlowRollbackEnabled) {
            authList.value = authorityList.filter(item => item.value != 'rollBack');
          } else {
            authList.value = authorityList;
          }
      });
      const handleCreate = () => {
        openModal(true, {
          isUpdate: false,
          tabKeys: ['2', '3', '4'],
        });
      };

      const handleEdit = async (record: Recordable) => {
        try {
          const params = {
            ...record,
            [`fieldWrite${record.id}`]: record.fieldWrite,
            [`fieldHide${record.id}`]: record.fieldHide,
            [`fieldExport${record.id}`]: record.fieldExport,
          };
          delete params.primaryKey;
          setProps({ loading: true });
          await getVisualUpdatePriv(params);
          createMessage.success(t('common.opSuccess'));
          reload();

          // 刷新角色-菜单页面
          if (window.opener && typeof(window.opener.refreshMenu)=='function') {
            window.opener.refreshMenu();
          }
        } catch (error) {
          console.error(error);
        } finally {
          setProps({ loading: false });
        }
      };

      const handleDelete = async (record: Recordable) => {
        try {
          await getVisualDelPriv({ id: record.id });
          createMessage.success(t('common.opSuccess'));
          reload();

          // 刷新角色-菜单页面
          if (window.opener && typeof(window.opener.refreshMenu)=='function') {
            window.opener.refreshMenu();
          }
        } catch (error) {
          console.error(error);
        } finally {
          setProps({ loading: false });
        }
      };

      const handleSuccess = async (users) => {
        try {
          if (users && users.length > 0) {
            let dataList: Recordable[] = [];
            users.forEach((item) => {
              let name = item.key;
              if (item.privType == 3) {
                name = item.code;
              }
              dataList.push({
                name: name,
                type: item.privType,
              });
            });
            const formData = {
              moduleCode: props.moduleCode,
              privs: dataList,
            };
            await getVisualCreatePriv(formData);
            reload();

            // 刷新角色-菜单页面
            if (window.opener && typeof(window.opener.refreshMenu)=='function') {
              window.opener.refreshMenu();
            }
          }
        } catch (error) {
          console.error(error);
        } finally {
          setProps({ loading: false });
        }
      };
      const [registerModalSelectFieldWriteText, { openModal: openSelectFieldWriteText }] =
        useModal();
      //可写字段打开
      const handleSelectFieldWriteText = (record, index, fields) => {
        currentRecord.value = {
          index,
          fields,
          id: record.id,
        };
        openSelectFieldWriteText(true, {
          type: index,
          isFetch: true,
          record: {
            formCode: props.formCode,
            fields: record[fields] ? record[fields].split(',') : '',
          },
        });
      };
      //可写字段回调
      const handleSuccessSelectFieldWriteText = async ({ fields, fieldTexts, type }) => {
        try {
          setProps({ loading: true });

          if (currentRecord.value.fields === 'fieldWrite') {
            await getVisualSetFieldWrite({
              id: currentRecord.value.id,
              fields,
            });
          } else if (currentRecord.value.fields === 'fieldHide') {
            await getVisualSetFieldHide({
              id: currentRecord.value.id,
              fields,
            });
          } else if (currentRecord.value.fields === 'fieldExport') {
            await getVisualSetFieldExport({
              id: currentRecord.value.id,
              fields,
            });
          }
          createMessage.success(t('common.opSuccess'));
          reload();
        } catch (error) {
          console.error(error);
        } finally {
          setProps({ loading: false });
        }
      };

      //过滤
      const [registerModalFilterModal, { openModal: openFilterModal }] = useModal();
      const handleFilterModal = (text, id, filterUnitCode) => {
        openFilterModal(true, {
          filterCond: text,
          formCode: props.formCode,
          mainId: id,
          filterUnitCode,
        });
      };
      const handleSuccessFilterModal = () => {
        reload();
      };
      const handleAuthorityChange = (e, record, col) => {
        if (col == 'manage') {
          authList.value.forEach((item) => {
            record[item.value] = e.target.checked ? 1 : 0;
          });
        } else {
          record[col] = e.target.checked ? 1 : 0;
        }
      };

      let source = 0; // 源目标数据序号
      let target = 0; // 目标数据序号
      // Table行拖拽
      function customRow(record, index) {
        return {
          props: {
            // draggable: 'true'
          },
          style: {
            // cursor: 'pointer',
          },
          // 鼠标移入
          onMouseenter: (event) => {
            // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
          },
          onMousedown: (event) => {
            console.log('event', event);
            event.stopPropagation();
            console.log('event', event.srcElement.tagName);
            if (event.srcElement.tagName === 'TD') {
              let cellIndex = event.srcElement.cellIndex;
              console.log('cellIndex', cellIndex);
              // 如果点击的是第1列（第0列为复选框列），则使可以拖动
              // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
              if (cellIndex == 1) {
                event.target.draggable = true; // 使可以拖动
              }
            }
          },
          // 开始拖拽
          onDragstart: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到源目标数据序号
            source = index;
            console.log(record, index, 'source');
            dataSource.value = getDataSource();
          },
          // 拖动元素经过的元素
          onDragover: (event) => {
            // 兼容 IE
            let ev = event || window.event;
            // 阻止默认行为
            ev.preventDefault();
          },
          // 鼠标松开
          onDrop: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到目标数据序号
            target = index;
            const dataFrom = dataSource.value[source];
            dataSource.value.splice(source, 1);
            dataSource.value.splice(target, 0, dataFrom);
            console.log('dataSource', dataSource.value);
            setTableData(dataSource.value);
            // event.target.parentElement.draggable = false; // 取消拖动
            // console.log(record, index, 'target', source, target);
          },
          onDblclick: () => {},
          onClick: (ev) => {
            console.log('onClick', ev);
            ev.stopPropagation();
          },
        };
      }

      //保存排序
      const handleUpdateOrders = () => {
        const data = getDataSource();
        if (data && data.length) {
          const arr: any[] = [];
          data.forEach((item, index) => {
            arr.push({
              id: item.id,
              order: index,
            });
          });
          setProps({ loading: true });
          getVisualUpdateOrders({
            orderList: JSON.stringify(arr),
          }).then((res) => {
            createMessage.success('操作成功');
            setProps({ loading: false });
            console.log('res', res);
          });
        }
      };
      return {
        registerTable,
        registerSelectAllModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelectFieldWriteText,
        handleSuccessSelectFieldWriteText,
        registerModalSelectFieldWriteText,
        registerModalFilterModal,
        handleSuccessFilterModal,
        handleFilterModal,
        authList,
        handleAuthorityChange,
        handleUpdateOrders,
      };
    },
  });
</script>
